package net.csdn.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;


/**
 * @author yuyang
 */
@Component
@Slf4j
public class TraceIdFilter implements Filter {

    public static final String TRACE_ID = "PFTID";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        long start = System.currentTimeMillis();
        String traceId = request.getHeader(TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(TRACE_ID, traceId);
        log.info("ip:[{}],path:[{}]", request.getRemoteAddr(), request.getRequestURI());
        filterChain.doFilter(request, resp);
        log.info("request path:[{}] end,used [{}]", request.getRequestURI(),(System.currentTimeMillis() - start));

    }

}